<template>
  <el-row class="chat-container">
    <!-- 左侧展示历史记录 -->
    <el-col :span="4" class="history-col">
      <div class="history-sidebar">
        <div class="header">
          <el-button type="primary" icon="el-icon-plus" @click="createNewSession" class="new-chat-btn">新建对话</el-button>
        </div>
        <el-menu class="session-list">
          <template v-if="groupedSessions.some(group => group.sessions.length > 0)">
            <template v-for="(group, index) in groupedSessions">
              <template v-if="group.sessions.length > 0">
                <el-menu-item-group :key="index" :title="group.title">
                  <el-menu-item v-for="session in group.sessions" :key="session.session_id"
                    @click="loadSessionMessages(session.session_id)"
                    :class="{ active: activeSessionId === session.session_id }">
                    <div class="session-item" @mouseenter="showDeleteButton = session.session_id"
                      @mouseleave="showDeleteButton = null">
                      <span class="title">{{ session.title || '未命名对话' }}</span>
                      <el-button v-if="showDeleteButton === session.session_id" type="text" icon="el-icon-delete"
                        @click.stop="deleteSession(session.session_id)" style="flex-shrink: 0;"></el-button>
                    </div>
                  </el-menu-item>
                </el-menu-item-group>
              </template>
            </template>
          </template>
          <template v-else>
            <div class="no-session-tip">
              暂无会话
            </div>
          </template>
        </el-menu>
      </div>
    </el-col>

    <!-- 右侧聊天区域 -->
    <el-col :span="20" class="chat-col">
      <div class="chat-area">
        <el-header class="chat-header">
          <!-- 头部内容 -->
          <div class="header-title-container">
            <el-avatar :src="aiAvatar" class="header-avatar"></el-avatar>
            <span class="header-title" style="width: 80%;">{{ currentSessionTitle }}</span>
          </div>
        </el-header>

        <el-main class="chat-main">
          <div class="messages-container" ref="messagesContainer" style="overflow-y: auto; overflow-x: hidden;">
            <div v-for="(message, index) in currentMessages" :key="index" class="message" :class="message.type">
              <div class="message-content">
                <el-avatar :src="message.type === 'user' ? userAvatar : aiAvatar" />
                <div class="message-bubble" :class="message.type === 'ai' ? 'chat-left' : 'chat-right'">
                  <!-- <vue-markdown :source="message.content" :options="markdownOptions" /> -->
                  <div v-html="parseMarkdown(message.content)" class="markdown-body"></div>
                </div>
                <div class="message-time">{{ formatTime(message.timestamp) }}</div>

              </div>
            </div>
          </div>
        </el-main>

        <el-footer class="chat-footer">
          <div class="input-area">
            <el-input v-model="userMessage" placeholder="输入您的问题（Shift+Enter换行）" type="textarea" :rows="2" resize="none"
              @keydown.enter.native.prevent="handleKeySubmit" />
            <el-button type="primary" :loading="isSending" @click="sendMessage" class="send-btn">发送</el-button>
          </div>
          <div class="hint-text">
            以上内容均为AI生成,仅供参考
          </div>
        </el-footer>
      </div>
    </el-col>
  </el-row>
</template>

<script scoped>
import service from '@/utils/httpRequest'
import { marked } from 'marked'
import hljs from 'highlight.js'
import DOMPurify, { sanitize } from 'dompurify'
import VueMarkdown from 'vue-markdown'
// 配置 marked 
marked.setOptions({
  highlight: (code, lang) => {
    const language = hljs.getLanguage(lang) ? lang : 'plaintext'
    return hljs.highlight(code, { language }).value
  },
  breaks: true, // 转换换行符为 <br>
  sanitize: false,
  gfm: true, // 启用 GitHub 样式
})
export default {
  data() {
    return {
      userId: this.$store.state.user.loginUser.id,
      userMessage: '',
      activeSessionId: null,
      historySessions: [],
      currentMessages: [],
      isSending: false,
      userAvatar: require('@/assets/user-avatar.png'),
      aiAvatar: require('@/assets/ai-avatar.png'),
      showDeleteButton: null,
      currentSessionTitle: '新对话',// 新增变量，初始化为未命名对话
      markdownOptions: {
        highlight: (code, lang) => {
          const language = hljs.getLanguage(lang) ? lang : 'plaintext';
          return hljs.highlight(code, { language }).value;
        },
        breaks: true, // 转换换行符为 <br>
        sanitize: false, // 如需安全过滤，可在解析后用 DOMPurify 处理
      }
    }
  },
  components: {
    VueMarkdown
  },

  created() {
    this.loadHistorySessions()
  },

  mounted() {

    this.$nextTick(() => {
      this.scrollToBottom();
    });
  },
  watch: {
    userMessage() {
      this.scrollToBottom();
    }
  },

  computed: {
    groupedSessions() {
      const today = new Date();
      today.setHours(0, 0, 0, 0);
      const yesterday = new Date(today);
      yesterday.setDate(yesterday.getDate() - 1);
      const theDayBeforeYesterday = new Date(today);
      theDayBeforeYesterday.setDate(theDayBeforeYesterday.getDate() - 2);
      const sevenDaysAgo = new Date(today);
      sevenDaysAgo.setDate(sevenDaysAgo.getDate() - 7);

      const todaySessions = [];
      const yesterdaySessions = [];
      const theDayBeforeYesterdaySessions = [];
      const sevenDaysSessions = [];
      const earlierSessions = [];

      this.historySessions.forEach(session => {
        const sessionDate = new Date(Number(session.start_timestamp));
        sessionDate.setHours(0, 0, 0, 0);

        if (sessionDate.getTime() === today.getTime()) {
          todaySessions.push(session);
        } else if (sessionDate.getTime() === yesterday.getTime()) {
          yesterdaySessions.push(session);
        } else if (sessionDate.getTime() === theDayBeforeYesterday.getTime()) {
          theDayBeforeYesterdaySessions.push(session);
        } else if (sessionDate >= sevenDaysAgo) {
          sevenDaysSessions.push(session);
        } else {
          earlierSessions.push(session);
        }
      });

      return [
        { title: '今天', sessions: todaySessions },
        { title: '昨天', sessions: yesterdaySessions },
        { title: '前天', sessions: theDayBeforeYesterdaySessions },
        { title: '七天内', sessions: sevenDaysSessions },
        { title: '更早', sessions: earlierSessions }
      ];
    }
  },

  methods: {
    async loadHistorySessions() {
      try {
        const res = await service.get('/ai/history')
        console.log(" 历史会话请求", res)
        if (res.code === 200) {
          this.historySessions = res.data
          console.log(" 历史会话", this.historySessions)
          this.historySessions.forEach(session => {
            // console.log('Session start timestamp:', session.start_timestamp);
          });
          if (this.historySessions.length > 0) {
            this.activeSessionId = this.historySessions[0].session_id
            this.loadSessionMessages(this.historySessions[0].session_id)
          }
        }
      } catch (error) {
        this.$message.error(' 加载历史记录失败')
      }
    },

    async createNewSession() {
      this.currentMessages = []
      this.activeSessionId = null
      this.currentSessionTitle = '新会话' // 新建对话时重置标题
    },

    async sendMessage() {
      //检查是否登录
      // console.log("发送消息登陆前检查", this.$store.state.user.loginUser)
      if (!this.$store.state.user.loginUser) {
        this.$message.error('请先登录');
        this.$router.push('/login');
        return;
      }
      if (!this.userMessage.trim()) return;
      console.log('BaseUrl', service.defaults.baseURL);
      this.isSending = true;
      const userMessage = this.userMessage;
      console.log('User message:', userMessage);
      this.userMessage = '';

      try {
        this.currentMessages.push({
          type: 'user',
          content: userMessage,
          timestamp: Date.now()
        });

        // 立即滚动到底部 
        this.scrollToBottom();

        const isNewSession = !this.activeSessionId;
        const endpoint = isNewSession ? 'ai/newsession' : 'ai/chat';
        // 1. 先渲染一个空 AI 消息占位
        this.currentMessages.push({
          type: 'ai',
          content: '',
          timestamp: Date.now()
        });
        this.scrollToBottom();

        // 2. 发起 fetch 请求
        const response = await fetch(service.defaults.baseURL + endpoint, {
          method: 'POST',
          headers: { "Content-Type": "application/json", 'Accept': 'application/octet-stream' },
          credentials: 'include', // 关键：允许携带 Cookie（同域/跨域）
          body: isNewSession? JSON.stringify({ userMessage }) : JSON.stringify({
            userMessage: userMessage,
            sessionId: this.activeSessionId
          })
        });

        // 检查响应状态码
        if (!response.ok) {
          throw new Error(`HTTP error! status: ${response.status}`);
        }

        const reader = response.body.getReader(); // ReadableStreamDefaultReader
        let done = false;
        while (true) {
          const { value, done } = await reader.read();
          if (done) break;
          const text = new TextDecoder().decode(value);
          console.log('receive text:', text);
          this.currentMessages[this.currentMessages.length - 1].content += text;
          this.$nextTick(() => {
            this.scrollToBottom();
          });
        }

        if (isNewSession) {
          this.loadHistorySessions();
        }
        this.isSending = false;
      } catch (error) {
        this.isSending = false;
        console.error('发送消息时出现错误:', error);
        // 可以添加更多的错误提示逻辑，比如使用 this.$message.error 显示错误信息
      }
    },

    async loadSessionMessages(sessionId) {
      try {
        const res = await service.get('/ai/record/one', { params: { sessionId } })
        console.log(" 会话记录请求", res)
        if (res.code === 200) {
          this.activeSessionId = sessionId
          this.currentMessages = res.data.messages.map(msg => {
            // console.log('Message timestamp:', msg.user_timestamp || msg.ai_timestamp);
            return {
              type: msg.user ? 'user' : 'ai',
              content: msg.user || msg.ai,
              timestamp: msg.user_timestamp || msg.ai_timestamp
            };
          });

          // 更新当前会话标题
          const currentSession = this.historySessions.find(session => session.session_id === sessionId);
          this.currentSessionTitle = currentSession ? currentSession.title || '新对话' : '新对话';

          // 加载完成后滚动到底部 
          this.scrollToBottom();
        }
      } catch (error) {
        this.$message.error(' 加载会话失败')
      }
    },

    formatTime(timestamp) {
      if (!timestamp) {
        console.error('Invalid timestamp:', timestamp);
        return '未知时间';
      }
      let ts = typeof timestamp === 'string' ? Date.parse(timestamp) : timestamp;
      if (isNaN(ts)) {
        console.error('Invalid timestamp:', timestamp);
        return '未知时间';
      }
      const date = new Date(ts);
      return `${date.getHours().toString().padStart(2, '0')}:${date.getMinutes().toString().padStart(2, '0')}`;
    },

    formatDate(timestamp) {
      // 类型转换（关键修复）
      const numericTimestamp = Number(timestamp)

      // 时区处理（参考[[5][8]]()）
      const dateObj = new Date(numericTimestamp)

      // 格式化输出（使用本地化API）
      return `
    ${dateObj.toLocaleDateString('zh-CN', {
        year: 'numeric',
        month: '2-digit',
        day: '2-digit'
      })} 
    ${dateObj.toLocaleTimeString('zh-CN', {
        hour12: false,
        hour: '2-digit',
        minute: '2-digit'
      })}
  `.replace(/\s+/g, ' ')
    },

    handleKeySubmit(e) {
      if (e.shiftKey) {
        this.userMessage += '\n'
      } else {
        this.sendMessage()
      }
    },

    parseMarkdown(content) {
      const rawHtml = marked.parse(content);
      
      return DOMPurify.sanitize(rawHtml);  // 安全过滤
    },

    // 新增滚动到底部的方法 
    scrollToBottom() {
      this.$nextTick(() => {
        const container = this.$refs.messagesContainer;
        if (container) {
          container.scrollTop = container.scrollHeight;
          console.log('滚动到底部', container.scrollTop, container.scrollHeight);
        }
      });
    },

    async deleteSession(sessionId) {
      this.$confirm('确定要删除该对话吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        try {
          await service.delete('/ai/delete', { params: { sessionId } });
          this.historySessions = this.historySessions.filter(session => session.session_id !== sessionId);
          if (this.activeSessionId === sessionId) {
            this.activeSessionId = null;
            this.currentMessages = [];
            this.currentSessionTitle = '未命名对话'; // 删除对话时重置标题
            if (this.historySessions.length > 0) {
              this.activeSessionId = this.historySessions[0].session_id;
              this.loadSessionMessages(this.activeSessionId);
            }
          }
          this.$message({
            type: 'success',
            message: '对话删除成功'
          });
        } catch (error) {
          this.$message.error('删除对话失败');
        }
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '取消删除'
        });
      });
    }
  }
}
</script>
<style lang="scss" scoped>
.markdown-body {
  overflow-x: auto;
  font-family: 'Segoe UI', sans-serif;
  padding: 0 10px;
  // background: #fff;
  border-radius: 6px;

  pre {
    background: #2d2d2d;
    color: #f8f8f2;
    padding: 1rem;
    border-radius: 5px;
    overflow-x: auto;
    white-space: pre-wrap !important;
    word-break: break-word !important;

  }

  code {
    font-family: 'Courier New', monospace;
    background-color: #f5f5f5;
    padding: 0.2em 0.4em;
    border-radius: 4px;
    white-space: pre-wrap !important;
    word-break: break-word !important;

  }
}

.chat-container {
  height: 100vh;
  // overflow: hidden;
  overflow-y: auto;

  .history-col {
    height: 100%;
    overflow: hidden;

    .history-sidebar {
      height: 100%;
      display: flex;
      flex-direction: column;
      background: white;
      border-right: 1px solid #e4e7ed;

      .header {
        padding: 15px;
        border-bottom: 1px solid #e4e7ed;
        flex-shrink: 0;
      }

      .session-list {
        flex: 1;
        overflow-y: auto;
        overflow-x: hidden; // 禁止水平滚动
        border-right: none;

        .el-menu-item {
          height: auto;
          padding: 8px 15px;
          /* 减小会话记录的上下内边距 */
          transition: all 0.3s;

          &.active {
            background: #f0f7ff;
          }

          .session-item {
            display: flex;
            justify-content: space-between;
            align-items: center;

            .title {
              font-size: 16px;
              /* 增大标题字体大小 */
              color: #303133;
              /* 新增样式控制标题溢出 */
              overflow: hidden;
              text-overflow: ellipsis;
              white-space: nowrap;
              max-width: calc(100% - 30px); // 预留删除按钮空间
            }
          }
        }

        .no-session-tip {
          display: flex;
          justify-content: center;
          align-items: center;
          height: 200px;
          color: #999;
          font-size: 24px;
          font-weight: bold;
        }
      }
    }
  }

  .chat-col {
    height: 100%;
    overflow: hidden;

    .chat-area {
      height: 100%;
      display: flex;
      flex-direction: column;

      .chat-header {
        height: 60px !important;
        flex-shrink: 0;
        border-bottom: 1px solid #e4e7ed;
        display: flex;
        align-items: center;
        padding: 0 20px;

        .header-title-container {
          display: flex;
          align-items: center;
        }

        .header-avatar {
          margin-right: 10px;
        }

        .header-title {
          font-size: 18px;
          color: #303133;
          overflow: hidden;
          text-overflow: ellipsis;
          font-weight: bold;
          white-space: nowrap;
          max-width: calc(100% - 50px); // 预留头像和一些间距空间
        }
      }

      .chat-main {
        height: calc(100vh - 120px);
        display: flex;
        flex-direction: column;
        flex: 0.94;

        .messages-container {
          flex: 1;
          overflow-y: auto;
          padding: 20px;
          box-sizing: border-box;

          .message {
            margin: 10px 0;
            width: 100%;

            &-content {
              display: flex;
              max-width: 100%;
              align-items: flex-start;

              .el-avatar {
                flex-shrink: 0;
                width: 40px;
                height: 40px;
              }
            }

            &-bubble {
              margin: 0 12px;
              max-width: 70%;
            }

            &-time {
              font-size: 12px;
              color: #909399;
              margin-top: 2px;
            }

            /* 用户消息样式 - 完全靠右 */
            &.user {
              display: flex;
              justify-content: flex-end;

              .message-content {
                flex-direction: row-reverse;
                // justify-content: ;
              }

              .message-bubble {
                white-space: normal;
                word-break: break-word;
              }

              .chat-right {
                background-color: #d1e5ff;
                text-align: left;
                border-top-right-radius: 0;
                padding: 4px 4px;
                margin-bottom: 4px;

                // pre {

                //   white-space: normal;
                //   word-break: break-all;
                //   overflow-x: auto;
                // }

                // code {
                //   white-space: normal;
                // }
              }
            }

            /* AI消息样式 - 靠左 */
            &.ai {
              .message-content {
                justify-content: flex-start;
              }

              .message-bubble {
                display: flex;
                flex-direction: column;
                align-items: flex-start;

                // pre {
                //   background: #f5f5f5;
                //   padding: 10px;
                //   border-radius: 8px;
                //   overflow-x: auto;
                //   /* 水平滚动条（可选） */
                // }

                // code {
                //   font-family: 'Courier New', monospace;
                // }
              }

              .chat-left {
                background-color: #fff0c2;
                text-align: left;
                width: 70%;
                border-top-left-radius: 0;
                padding: 8px 12px;
                margin-bottom: 4px;

                // pre {
                //   white-space: pre-wrap;
                //   word-break: break-all;
                //   overflow-x: auto;
                // }

                // code {
                //   white-space: pre-wrap;
                // }
              }
            }
          }

          /* 消息气泡基础样式 */
          .chat-left,
          .chat-right {
            display: inline-block;
            box-sizing: border-box;
            border-radius: 12px;
            line-height: 24px;
            max-width: 100%;
            white-space: normal;
            position: relative;
          }

          /* 可选：添加小三角指示器 */
          .chat-right:after {
            content: '';
            position: absolute;
            right: -8px;
            top: 12px;
            width: 0;
            height: 0;
            border: 8px solid transparent;
            border-left-color: #d1e5ff;
            border-right: 0;
          }

          .chat-left:before {
            content: '';
            position: absolute;
            left: -8px;
            top: 12px;
            width: 0;
            height: 0;
            border: 8px solid transparent;
            border-right-color: #fff0c2;
            border-left: 0;
          }
        }
      }

      .chat-footer {
        padding-bottom: 20px;

        .input-area {
          position: relative;
          padding: 10px 15px;
          background: white;
          box-shadow: 0 4px 12px rgba(0, 0, 0, 0.03);
          margin-top: -20px;

          ::v-deep .el-textarea {
            &__inner {
              padding: 16px 0px 16px 16px !important;
              min-height: 6px !important;
              line-height: 1.6;
              border-radius: 12px;
              transition: all 0.3s;
              box-shadow: 0 2px 6px rgba(0, 0, 0, 0.05);

              &:focus {
                border-color: #409EFF;
                box-shadow: 0 4px 12px rgba(64, 158, 255, 0.2);
              }
            }
          }

          .send-btn {
            position: absolute;
            right: 32px;
            bottom: 40px;
            padding: 8px 20px;
            border-radius: 8px;
            background: linear-gradient(135deg, #409EFF, #3375ff);
            border: none;
            transition: all 0.3s;

            &:hover {
              transform: translateY(-1px);
              box-shadow: 0 4px 8px rgba(64, 158, 255, 0.35);
            }

            &.is-loading {
              opacity: 0.8;
            }
          }
        }
      }
    }
  }
}

.hint-text {
  text-align: center;
  font-size: 12px;
  color: #999;
  margin-top: 10px;
}

.session-list {
  text-align: left;
}
</style>